package com.funtl.screw.admin.config;

import cn.hutool.core.util.StrUtil;
import com.funtl.screw.admin.service.SysOauthClientDetailsService;
import com.funtl.screw.common.core.constant.CacheConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * oauth 客户端认证参数初始化
 *
 * @author lusifer
 */
@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings("all")
public class ClientDetailsInit {

    private final SysOauthClientDetailsService clientDetailsService;

    private final RedisTemplate redisTemplate;

    @Async
    @Order
    @EventListener({WebServerInitializedEvent.class, ClientDetailsInitEvent.class})
    public void initClientDetails() {
        log.debug("初始化客户端信息开始 ");
        clientDetailsService.list().stream().filter(client -> {
            return StrUtil.isNotBlank(client.getAdditionalInformation());
        }).forEach(client -> {
            String key = String.format("%s:%s", CacheConstants.CLIENT_FLAG, client.getClientId());
            redisTemplate.opsForValue().set(key, client.getAdditionalInformation());
        });
        log.debug("初始化客户端信息结束 ");
    }

    /**
     * 客户端刷新事件
     */
    public static class ClientDetailsInitEvent extends ApplicationEvent {
        public ClientDetailsInitEvent(Object source) {
            super(source);
        }
    }
}
